package com.example.fileLock;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.Calendar;

public class ThreadWriteFile extends Thread {

	private String filePath;

	public ThreadWriteFile(String filePath) {
		this.filePath = filePath;
	}

	public void run() {
		Calendar calstart = Calendar.getInstance();
		File file = new File(filePath);
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			// 对该文件加锁
			RandomAccessFile out = new RandomAccessFile(file, "rw");
			FileChannel fcout = out.getChannel();
			FileLock flout = null;
			while (true) {
				String threadName = Thread.currentThread().getName();
				System.out.println("============当前线程名称：" + threadName);
				try {
					// flout = fcout.tryLock(); //非阻塞
					flout = fcout.lock(); // 阻塞
					break;
				} catch (Exception e) {
					System.out.println("有其他线程正在操作该文件");
				}
			}
			for (int i = 1; i <= 1000; i++) {
				StringBuffer sb = new StringBuffer();
				sb.append("这是第" + i + "行，应该没啥错哈" + System.getProperty("line.separator"));
				out.write(sb.toString().getBytes("utf-8"));
			}
			flout.release();
			fcout.close();
			out.close();
			out = null;
		} catch (IOException e) {
			e.printStackTrace();
		}
		Calendar calend = Calendar.getInstance();
		System.out.println("写文件共花了" + (calend.getTimeInMillis() - calstart.getTimeInMillis()) + "秒");
	}

}
